package ru.smc.hogwarts.servlets.subjects;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Person;
import ru.smc.hogwarts.model.Subject;

public class SubjectsEdit extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String error = "";
	private int professor = 0;
	private String name = null;
	private int auditorium = 0;
	private int year = 0;
	private String type = null;
	private HttpSession session;
       
    public SubjectsEdit() {
        super();
    }

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int id = 0;
		request.setAttribute("error", error);
		
		session = request.getSession(true);
    	session.setAttribute("servletName", getServletName());
		
		try {
			id = Integer.parseInt(request.getParameter("id"));
		} catch(NumberFormatException e) {}
		
		EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
		
		Subject subject = em.find(Subject.class, id);
		
		if (subject == null) {
			request.getRequestDispatcher("/pages/error/error.jsp").forward(request, response);
		} else {		
			String select = "select p " +
			"from Person p " +
			"where (p.role.name = 'professor' " +
			"or p.role.name = 'head' " +
			"or p.role.name = 'head_house') " +
			"and p.id not in (select s.professor.id from Subject s)";
		
			List<Person> professors = new ArrayList<Person>();
			if (subject.getProfessor() != null)
				professors.add(em.find(Person.class, subject.getProfessor().getId()));
			professors.addAll(em.createQuery(select).getResultList());
			request.setAttribute("professors", professors);
				
			if (error == "") {
				if (subject.getProfessor() != null)
					request.setAttribute("professor", subject.getProfessor().getId());
				request.setAttribute("name", subject.getName());
				request.setAttribute("auditorium", subject.getAuditorium());
				request.setAttribute("year", subject.getYear());
				request.setAttribute("type", subject.getType());
			} else if (error != "") {
				request.setAttribute("professor", professor);
				request.setAttribute("name", name);
				request.setAttribute("auditorium", auditorium);
				request.setAttribute("year", year);
				request.setAttribute("type", type);
			}
			
			request.setAttribute("id", id);
							
			error = "";
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/pages/subjects/subjectEdit.jsp");
			dispatcher.forward(request, response);
		}

		em.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		error = "";
		int id = 0;
		
		try {
			try {
				id = Integer.parseInt(request.getParameter("id"));
			} catch(NumberFormatException e) {}
			
			name = request.getParameter("name");
			if (name == "") 
				error += "<span>П</span>оле \"Название\" не должно быть пустым.<br>";

			if (request.getParameter("auditorium") == "") {
				error += "<span>П</span>оле \"Аудитория\" не должно быть пустым.<br>";
			} else {
				if (request.getParameter("auditorium").matches("^[0-9]+$")) {
					auditorium = Integer.parseInt(request.getParameter("auditorium"));
				} else {
					error += "<span>П</span>оле \"Аудитория\" должно содержать цифры.<br>";
				}				
			}

			if (request.getParameter("year") == "") {
				error += "<span>П</span>оле \"Курс\" не должно быть пустым.<br>";
			} else {
				year = Integer.parseInt(request.getParameter("year"));
			}
			
			type = request.getParameter("type");
			if (type == "") 
				error += "<span>П</span>оле \"Тип\" не должно быть пустым.<br>";
			
			if (request.getParameter("professor") == "") {
				professor = 0;
			} else {
				professor = Integer.parseInt(request.getParameter("professor"));
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		if (error == "") { 
			this.updateSubject(id, name, professor, auditorium, year, type);
			response.sendRedirect(request.getContextPath() + "/subjects");
		} else if (error != "") {
			response.sendRedirect(request.getContextPath() + "/subjects/edit?id="+id);
		}
	}
	
	public void updateSubject(int editorId, String name, 
			int professor, int auditorium, int year, String type) {
		EntityManagerFactory emf = EMF.getInstance().getEMF();
    	EntityManager em = emf.createEntityManager();
		
		em.getTransaction().begin();
		Subject subject = em.find(Subject.class, editorId);
		Person _professor = null;
		if (professor != 0) {
			_professor = em.find(Person.class, professor);
		}
		
		subject.setProfessor(_professor);
		subject.setName(name);
		subject.setAuditorium(auditorium);
		subject.setYear(year);
		subject.setType(type);
		em.getTransaction().commit();
		
		em.close();
	}

}
